/**
 * 问题库
 */
import React, { Component } from "react";
import { connect } from "dva";
import { routerRedux } from "dva/router";
import { Card, Button, Modal, Table, Input, Divider, Select, Row, Col, Icon, message, Spin } from "antd";
import styles from './knowledgeGather.less';
import {
	getGenerateAnswersDetail, getGenerateAnswersDelRelPara, getGenerateAnswersAnswerPara,
	postGenerateAnswersReGenerate, getGenerateAnswersCancelOperate, getGenerateAnswersReSearch,
	getGenerateAnswersChangePosition, postGenerateAnswersReOperate, postGenerateAnswersEdit,
} from '@/services/knowledgeGather';
import MarkdownEditor from "@/utils/vditorEdit";

const { Option } = Select;

class PreviewQADetail extends Component {
	constructor(props) {
		super(props);
		this.state = {
			qaDataDetail: null,
			fragmentList: [],
			fragmentContent: '',
			question: '',
			similarQuestion: '',
			questionList: [],
			answerContent: '',
			isGenerateAnswer: false,
			isDelOperate: false,
			isCompleteSelect: false,
			fragmentOperationStatus: 'edit', // 列表状态：default；编辑状态：edit；搜索状态：search；
			isReDenerateAnswer: false,
			isCompleteDel: false,
			saveLoading: false,
		};
	}

	componentDidMount() {
		this.getQaDetail()
	}

	getQaDetail = async () => {
		const { location: { query: { id } } } = this.props;
		let res = await getGenerateAnswersDetail({ id });
		console.log(res);
		this.setState({
			qaDataDetail: res,
			question: res.question,
			answerContent: res.content,
			fragmentList: res.paraVoList,
			questionList: res.similarQuestionsList,
			// isGenerateAnswer: res.isShowMenu ? true : false,
			// isDelOperate: res.isShowMenu ? true : false,
			// fragmentOperationStatus: res.isShowMenu ? '' : 'edit'
		})
	}

	removeQuestion = question => {
		let { questionList } = this.state;
		questionList = questionList.filter(item => item != question);
		this.setState({ questionList });
	};

	render() {
		const {
			question, similarQuestion, qaDataDetail, fragmentList, fragmentOperationStatus, questionList, saveLoading,
			isReDenerateAnswer, isGenerateAnswer, isDelOperate, isCompleteDel, isCompleteSelect, fragmentContent,
		} = this.state;
		const antIcon = <Icon type="loading" style={{ fontSize: 24 }} spin />;

		return (
			<div className={styles['question-library']}>
				<Spin tip="重新生成答案中..." spinning={isReDenerateAnswer} indicator={antIcon}>
					<Card bordered={false}>
						<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
							<div style={{ display: 'flex', gap: "20px" }}>
								<Button type="primary" onClick={this.revertRouter}>返回列表</Button>
								{/* <Button icon="sync" onClick={this.getQaDetail}>刷新</Button> */}
							</div>
							<div style={{ display: 'flex', gap: "20px", alignItems: 'center' }}>
								<div>
									<label style={{ marginRight: 12 }}>阅览范围</label>
									<Select style={{ width: 100 }} defaultValue="Read">
										<Option value="All">全部</Option>
										<Option value="Read">已阅</Option>
										<Option value="Unreviewed">未阅</Option>
									</Select>
								</div>
								<Button type="primary" onClick={() => this.setGenerateAnswerPosition('2')}>上一条</Button>

								<Button type="primary" onClick={() => this.setGenerateAnswerPosition('1')}>下一条</Button>
							</div>
						</div>
						<Divider />
						<Row gutter={30}>
							<Col span={12}>
								<div>
									<div style={{ marginBottom: 20 }}>
										<div style={{ display: 'flex', gap: '20px' }}>
											<label style={{ fontWeight: 'bold', fontSize: '18px' }}>答案来源片段：</label>
											{/* {fragmentOperationStatus === 'default' ? (
												<Button type="primary" onClick={this.editFragment}>编辑片段</Button>
											) : null} */}
											{/* {isDelOperate ? (
												<Button type="danger" onClick={this.setCancelOperate}>取消操作</Button>
											) : null} */}
											{/* {fragmentOperationStatus === 'edit' ? (
												<Button type="primary" onClick={this.setQueryFragment}>重新搜索片段</Button>
											) : null} */}
											{isCompleteSelect ? (
												<Button type="primary" onClick={this.setCompleteSelect}>完成选择</Button>
											) : null}
											{isCompleteDel ? (
												<Button type="primary" onClick={this.setCompleteDel}>完成操作</Button>
											) : null}
											{isGenerateAnswer ? (
												<Button type="primary" onClick={this.setGenerateAnswer}>重新生成答案</Button>
											) : null}
										</div>
									</div>
									<div style={{ height: 'calc(100vh - 320px)', overflowY: 'scroll', paddingRight: '10px' }}>
										{/* {fragmentOperationStatus === 'search' ? ( */}
										<Input.Search
											placeholder="输入关键词"
											value={fragmentContent}
											onChange={e => this.setState({ fragmentContent: e.target.value })}
											onSearch={value => this.onQuerySearch(value)}
											style={{ width: '100%', marginBottom: 20 }}
										/>
										{/* ) : null} */}
										<div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
											{fragmentList && fragmentList.map((item, index) => (
												<div style={{ width: '100%', display: 'flex', gap: '12px' }}>
													<div style={{ flex: 1, background: '#E8E8E8', padding: '12px 0', borderRadius: 10 }}>
														<div style={{ padding: '0 12px', display: 'flex', justifyContent: 'space-between' }}>
															<div style={{ display: 'flex', gap: '20px' }}>
																<span>片段 {index + 1}</span>
																<span>{((item.score.toFixed(2)) * 1000 / 10) + '%'}</span>
															</div>
															{fragmentOperationStatus === 'edit' ? (
																<div style={{ display: 'flex', gap: '12px' }}>
																	<Button size="small" type="danger" style={{ width: 60 }} onClick={() => this.removeFragment(item)}>删除</Button>
																</div>
															) : null}
															{fragmentOperationStatus === 'search' && item.isChoose !== null ? (
																<div style={{ display: 'flex', gap: '12px' }}>
																	{item.isChoose ? (
																		<Button size="small" type="primary" style={{ width: 60 }} onClick={() => this.setSelectReOperate(item, 2)}>已选择</Button>
																	) : (
																		<Button size="small" style={{ width: 60 }} onClick={() => this.setSelectReOperate(item, 1)}>选择</Button>
																	)}
																	{/* <Button size="small" style={{ width: 60 }}>选择</Button> */}
																	{/* <Button size="small" type="primary" style={{ width: 60 }}>已选择</Button> */}
																</div>
															) : null}
														</div>
														<Divider style={{ margin: '12px 0', background: '#D5D5D5' }} />
														<div style={{ padding: '0 12px' }}>{item.content}</div>
													</div>
												</div>
											))}
										</div>
									</div>
								</div>
							</Col>
							<Col span={12}>
								<div>
									<div style={{ marginBottom: 20, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
										<label style={{ fontWeight: 'bold', fontSize: '18px' }}>知识点详情：</label>
										<Button type="primary" onClick={this.onQaSave} loading={saveLoading}>保存</Button>
									</div>
									<div style={{ height: 'calc(100vh - 320px)', overflowY: 'scroll', paddingRight: '10px' }}>
										<div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
											<div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
												<label style={{ fontWeight: 'bold' }}>标准问</label>
												<Input value={question} onChange={e => this.setQuestion(e, 'question')} placeholder="请输入标准问" style={{ backgroundColor: '#FFFFFF' }} />
											</div>
											<div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
												<label style={{ fontWeight: 'bold' }}>答案</label>
												<div>
													<MarkdownEditor
														value={this.state.answerContent}
														name='markdown-editor'
														id='markdown-editor'
														height='300px'
														width='700'
														onChange={value => this.setState({ answerContent: value })}
														ref={(r) => (this.vEditor = r)}
													/>
												</div>
											</div>
											<div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
												<label style={{ fontWeight: 'bold' }}>相似问</label>
												<div style={{ display: 'flex', flexDirection: 'column', gap: '10px', marginBottom: 20 }}>
													<div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
														<Input value={similarQuestion} onChange={e => this.setQuestion(e, 'similarQuestion')} placeholder="添加相似问" />
														<Icon type="plus-square" onClick={this.setAddQuestion} style={{ fontSize: '20px' }} />
													</div>
													{questionList && questionList.length > 0 && questionList.map((question, index) => (
														<div key={index} style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
															<Input value={question} placeholder="请输入相似问" style={{ backgroundColor: '#FFFFFF' }} />
															<Icon type="minus-square" style={{ fontSize: '20px' }} onClick={() => this.removeQuestion(question)} />
														</div>
													))}
												</div>
											</div>
										</div>
									</div>
								</div>
							</Col>
						</Row>
					</Card>
				</Spin>
			</div>
		);
	}

	revertRouter = () => {
		const { dispatch } = this.props;
		let pathname = "/knowledgeDesign/knowledgeCollect/questionAnswerList";
		dispatch(routerRedux.push({ pathname }));
	}

	removeFragment = async (row) => {
		const { location: { query: { id } } } = this.props;
		const that = this;
		Modal.confirm({
			title: '是否确定删除该片段',
			okText: '确定',
			okType: 'danger',
			cancelText: '取消',
			onOk: async () => {
				let obj = { id, paraId: row.paraId };
				let res = await getGenerateAnswersDelRelPara(obj);
				console.log(res);
				if (res.code === 0) {
					this.setState({ isCompleteDel: true });
					this.getAnswerPara();
				}
			},
			onCancel() { },
		});
	}

	getAnswerPara = async () => {
		const { location: { query: { id } } } = this.props;
		let res = await getGenerateAnswersAnswerPara({ id });
		console.log(res);
		this.setState({ fragmentList: res })
	}

	// 重新生成答案
	setGenerateAnswer = async () => {
		const { location: { query: { id } } } = this.props;
		this.setState({ isReDenerateAnswer: true })
		let res = await postGenerateAnswersReGenerate({ id });
		console.log(res);
		if (res.code === 0) {
			this.setState({ isReDenerateAnswer: false })
			if (res.data) {
				this.setState({
					isGenerateAnswer: false,
					isCompleteDel: false,
					isCompleteSelect: false,
					fragmentOperationStatus: 'edit'
				}, () => this.getQaDetail());
			} else {
				message.error(res.message)
			}
		} else {
			let timer = setTimeout(() => {
				this.setState({ isReDenerateAnswer: false }, () => clearTimeout(timer))
			}, 5000)
		}
	}

	onQuerySearch = value => {
		this.setState({
			fragmentContent: value,
			isGenerateAnswer: false,
			isCompleteDel: false,
			isCompleteSelect: false,
		}, () => this.queryAnswerPara())
	}

	editFragment = () => {
		this.setState({ fragmentOperationStatus: 'edit', isDelOperate: true })
	}

	setCompleteSelect = () => {
		this.setState({
			isGenerateAnswer: true,
			isCompleteDel: false,
			isCompleteSelect: false,
			fragmentOperationStatus: 'edit',
		}, () => this.getQaDetail())
	}

	setCompleteDel = () => {
		this.setState({
			isGenerateAnswer: true,
			isCompleteDel: false,
			isCompleteSelect: false,
			fragmentOperationStatus: 'edit',
		}, () => this.getQaDetail())
	}

	// 取消操作
	setCancelOperate = async () => {
		const { location: { query: { id } } } = this.props;
		let res = await getGenerateAnswersCancelOperate({ id });
		console.log(res);
		if (res.code === 0) {
			this.setState({
				isGenerateAnswer: false,
				fragmentOperationStatus: 'edit',
				isDelOperate: false,
			});
			this.getQaDetail();
		}
	}

	setQueryFragment = () => {
		this.setState({
			fragmentOperationStatus: 'search',
			isDelOperate: true
		}, () => {
			this.queryAnswerPara()
		})
	}

	// 搜索片段
	queryAnswerPara = async () => {
		const { location: { query: { id } } } = this.props;
		let { fragmentContent } = this.state;
		let res = await getGenerateAnswersReSearch({ id, text: fragmentContent });
		console.log(res);
		this.setState({
			fragmentList: res,
			fragmentOperationStatus: 'search',
		})
	}

	// 选择片段 or 取消选择
	setSelectReOperate = async (row, type) => {
		const { location: { query: { id } } } = this.props;
		let obj = { id, score: row.score, paraId: row.paraId, type };
		let res = await postGenerateAnswersReOperate(obj);
		console.log(res);
		if (res.code === 0) {
			this.setState({ isGenerateAnswer: false, isCompleteDel: false, isCompleteSelect: true });
			this.queryAnswerPara();
		}
	}

	// 下一条 or 上一条
	setGenerateAnswerPosition = async type => {
		const { location: { query: { id } } } = this.props;
		let res = await getGenerateAnswersChangePosition({ id, type });
		console.log(res);
		if (res.code === 0) {
			if (res.data && res.data != '') {
				const { dispatch } = this.props;
				let pathname = "/knowledgeDesign/knowledgeCollect/previewQADetail";
				dispatch(routerRedux.push({ pathname, query: { id: res.data } }));
				this.getQaDetail()
			} else {
				let text = "";
				switch (type) {
					case '1':
						text = "当前已是最后一条"
						break;

					case '2':
						text = "当前已是第一条"
						break;

					default:
						break;
				};
				message.error(text)
			}
		}
	}

	setQuestion = (e, type) => {
		this.setState({ [type]: e.target.value })
	}

	setAddQuestion = e => {
		e.stopPropagation();
        e.preventDefault();
		let { similarQuestion, questionList } = this.state;
		if (questionList.indexOf(similarQuestion) >= 0) {
			return message.error(`【${similarQuestion}】问题已存在`)
		};
		questionList.unshift(similarQuestion);
		this.setState({ similarQuestion: "", questionList });
	}

	onQaSave = e => {
		e.stopPropagation();
        e.preventDefault();
		const { location: { query: { id } } } = this.props;
		const { question, answerContent, similarQuestion, questionList } = this.state;
		if (question == '' || question == null || question == undefined) {
			return message.error("请输入标准问题");
		}
		if (answerContent == '' || answerContent == null || answerContent == undefined) {
			return message.error("请输入或者生成问题答案");
		}
		let similarQuestionList = [];
		if (similarQuestion == '' || similarQuestion == null || similarQuestion == undefined) {
			if (questionList && questionList.length > 0) {
				similarQuestionList = [...questionList];
			}
		} else {
			if (questionList && questionList.length > 0) {
				if (questionList.indexOf(similarQuestion) >= 0) {
					similarQuestionList = [...questionList];
				} else {
					similarQuestionList = [similarQuestion, ...questionList];
				}
			} else {
				similarQuestionList = [similarQuestion];
			}
		};
		this.setState({ saveLoading: true }, async () => {
			let obj = {
				id, question, content: answerContent, similarQuestionsList: similarQuestionList,
			};
			let res = await postGenerateAnswersEdit(obj);
			console.log(res);
			if (res.code === 0) {
				message.success('保存成功');
				this.setState({ saveLoading: false })
			}
		})
	}
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(PreviewQADetail);
